#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/7/16  12:40
# @Author: 余浪人
# @email: yulangren520@gmail.com
from flask_login import login_required
import platform, psutil, datetime
from apps.control import sys_bp
from flask import render_template, request, jsonify, current_app
from apps.forms.system_form import TL_System_Form, TL_Ad_Form, TL_Blogroll_Form, TL_Redis_Form, TL_Notice_Form, TL_Pay_Form, TL_Email_Form, TL_Save_Form
from apps.lib.cache_sys import sys_cache, cache
from apps.lib.public import edit_data, add_data, check_obj, real_delete_data, real_deletes, page_auto
from apps.lib.token import Verify_authorization
from apps.models.content_model import TL_Content_Model, TL_Column_model
from apps.models.system_model import db, TL_System_Model, TL_Ad_Model, TL_Blogroll_Model, TL_Redis_Model, TL_Notice_Model, \
    TL_PayConf_Model, TL_Email_Model, TL_Save_Model


@sys_bp.route('/manage', endpoint='base_frame', methods=['GET'])
@login_required
def base_frame():
    return render_template('system_template/base_frame.html')


@sys_bp.route('/top_frame', endpoint='top_frame', methods=['GET'])
@login_required
def top_frame():
    return render_template('system_template/top_frame.html')


@sys_bp.route('/left_frame', endpoint='left_frame', methods=['GET'])
@login_required
def left_frame():
    return render_template('system_template/left_frame.html')


@sys_bp.errorhandler(404)
def not_found_error(error):
    return render_template('error_template/error_400.html'), 200


@sys_bp.route('/main_frame', endpoint='main_frame', methods=['GET'])
@login_required
def main_frame():
    # ************ 数据统计  ***************
    doc_count = TL_Content_Model.query.filter().count()
    col_count = TL_Column_model.query.filter().count()
    ad_count = TL_Ad_Model.query.filter().count()
    link_count = TL_Blogroll_Model.query.filter().count()
    # ************ 运行天数  ***************
    boot_time = TL_System_Model.query.first().create_time.strftime('%Y-%m-%d').split('-')
    current = datetime.datetime.now().strftime('%Y-%m-%d').split('-')
    d1 = datetime.datetime(int(boot_time[0]), int(boot_time[1]), int(boot_time[2]))
    d2 = datetime.datetime(int(current[0]), int(current[1]), int(current[2]))
    has_run = (d2 - d1).days  # 已运行天数
    # ************ 内存信息  ***************
    mem = psutil.virtual_memory()
    total = str(round(mem.total / 1024 / 1024))  # 当前的内存大小
    used = str(round(mem.used / 1024 / 1024))  # 已使用
    use_per = str(round(mem.percent))  # 已使用百分比
    free = str(round(mem.free / 1024 / 1024))  # 可用
    # ************ 系统信息  ***************
    sys_os = platform.system()
    version = '0.1'
    # ************ 更新文档信息  ***************
    doc_list = TL_Content_Model.query.order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status != -1).limit(10).all()

    data = {
        "count": {"doc": doc_count, "col": col_count, "ad": ad_count, "link": link_count}, "version": version,
        "sys_os": sys_os, 'mem': {"total": total, "used": used, "use_per": use_per, "free": free},
        "sys_has_run": has_run, "doc_list": doc_list
    }
    return render_template('system_template/main_frame.html', data=data)


@sys_bp.route('/favicon.ico', endpoint='favicon', methods=['GET'])
def favicon():
    sys = sys_cache()
    path = sys.web_ico[1:]
    if len(path) < 10: path = 'images/favicon.ico'
    return current_app.send_static_file(path)


# *************************  系统功能开发  ***************************************
# 系统设置
@sys_bp.route('/system', endpoint='system', methods=['GET', 'POST'])
@login_required
def system():
    sys_obj = TL_System_Model.query.first()
    if request.method == 'POST':
        cache.delete('sys_cache')
        return edit_data(TL_System_Form, TL_System_Model, db, sys_obj.id)
    form = TL_System_Form(data=dict(sys_obj))
    return render_template('system_template/system.html', form=form)


# 系统公告列表
@sys_bp.route('/notice_list', endpoint='notice_list', methods=['GET', 'DELETE', 'DELETES'])
@login_required
def notice_list():
    if request.method == 'DELETE':
        return real_delete_data(TL_Notice_Model, db, request.form.get('uid'))
    elif request.method == 'DELETES':
        return real_deletes(TL_Notice_Model, db, request.form.get('id_array').split('#TL#'))
    data_list, page = page_auto(TL_Notice_Model.query.order_by(TL_Notice_Model.id.desc()))
    return render_template('system_template/notice_list.html', data_list=data_list, page=page)


# 公告添加
@sys_bp.route('/notice', endpoint='notice', methods=['GET', 'POST'])
@login_required
@Verify_authorization
def notice():
    if request.method == 'POST':
        return add_data(TL_Notice_Model, TL_Notice_Form, db)
    return render_template('system_template/notice.html', form=TL_Notice_Form())


# 公告修改
@sys_bp.route('/notice_edit_<int:id>', endpoint='notice_edit', methods=['GET', 'POST'])
@login_required
def notice_edit(id):
    notice_obj = TL_Notice_Model.query.filter_by(id=id).first()
    if request.method == 'POST' and not check_obj(notice_obj):
        return edit_data(TL_Notice_Form, TL_Notice_Model, db, notice_obj.id)
    if not check_obj(notice_obj):
        return render_template('system_template/notice.html', form=TL_Notice_Form(data=dict(notice_obj)))


# 广告列表
@sys_bp.route('/advertising_list', endpoint='advertising_list', methods=['GET', 'DELETE', 'DELETES'])
@login_required
def advertising_list():
    if request.method == 'DELETE':
        return real_delete_data(TL_Ad_Model, db, request.form.get('uid'))
    elif request.method == 'DELETES':
        return real_deletes(TL_Ad_Model, db, request.form.get('id_array').split('#TL#'))
    data_list, page = page_auto(TL_Ad_Model.query.order_by(TL_Ad_Model.id.desc()))
    return render_template('system_template/advertising_list.html', data_list=data_list, page=page)


# 广告添加
@sys_bp.route('/advertising', endpoint='advertising', methods=['GET', 'POST'])
@login_required
@Verify_authorization
def advertising():
    if request.method == 'POST':
        return add_data(TL_Ad_Model, TL_Ad_Form, db)
    return render_template('system_template/advertising.html', form=TL_Ad_Form())


# 广告修改
@sys_bp.route('/advertising_<int:id>', endpoint='advertising_edit', methods=['GET', 'POST'])
@login_required
def advertising_edit(id):
    ad_obj = TL_Ad_Model.query.filter_by(id=id).first()
    if request.method == 'POST' and not check_obj(ad_obj):
        return edit_data(TL_Ad_Form, TL_Ad_Model, db, id)
    if not check_obj(ad_obj):
        return render_template('system_template/advertising.html', form=TL_Ad_Form(data=dict(ad_obj)))


# 友情列表
@sys_bp.route('/blogroll_list', endpoint='blogroll_list', methods=['GET', 'DELETE', 'DELETES'])
@login_required
def blogroll_list():
    if request.method == 'DELETE':
        return real_delete_data(TL_Blogroll_Model, db, request.form.get('uid'))
    elif request.method == 'DELETES':
        return real_deletes(TL_Blogroll_Model, db, request.form.get('id_array').split('#TL#'))
    data_list, page = page_auto(TL_Blogroll_Model.query.order_by(TL_Blogroll_Model.id.desc()))
    return render_template('system_template/blogroll_list.html', data_list=data_list, page=page)


# 友情添加
@sys_bp.route('/blogroll', endpoint='blogroll', methods=['GET', 'POST'])
@login_required
@Verify_authorization
def blogroll():
    if request.method == 'POST':
        return add_data(TL_Blogroll_Model, TL_Blogroll_Form, db)
    return render_template('system_template/blogroll.html', form=TL_Blogroll_Form())


# 友情修改
@sys_bp.route('/blogroll_<int:id>', endpoint='blogroll_edit', methods=['GET', 'POST'])
@login_required
def blogroll_edit(id):
    link_obj = TL_Blogroll_Model.query.filter_by(id=id).first()
    if request.method == 'POST' and not check_obj(link_obj):
        return edit_data(TL_Blogroll_Form, TL_Blogroll_Model, db, id)
    if not check_obj(link_obj):
        return render_template('system_template/blogroll.html', form=TL_Blogroll_Form(data=dict(link_obj)))


# 支付配置
@sys_bp.route('/pay_conf', endpoint='pay_conf', methods=['GET', 'POST'])
@login_required
def pay_conf():
    payConf = TL_PayConf_Model.query.filter_by().first()
    if request.method == 'POST' and not check_obj(payConf):
        return edit_data(TL_Pay_Form, TL_PayConf_Model, db, payConf.id)
    if not check_obj(payConf):
        return render_template('system_template/pay_conf.html', form=TL_Pay_Form(data=dict(payConf)))


# 缓存配置(redis)
@sys_bp.route('/redis_conf', endpoint='redis_conf', methods=['GET', 'POST'])
@login_required
def redis_conf():
    redis_obj = TL_Redis_Model.query.first()
    if request.method == 'POST':
        try:
            return edit_data(TL_Redis_Form, TL_Redis_Model, db, redis_obj.id)
        except:
            return jsonify({"status": -1, "msg": "保存成功,可能连接异常!"})
    form = TL_Redis_Form(data=dict(redis_obj))
    return render_template('system_template/redis_conf.html', form=form)


# Email配置
@sys_bp.route('/email_conf', endpoint='email_conf', methods=['GET', 'POST'])
@login_required
def email_conf():
    email_obj = TL_Email_Model.query.first()
    if request.method == 'POST':
        return edit_data(TL_Email_Form, TL_Email_Model, db, email_obj.id)
    form = TL_Email_Form(data=dict(email_obj))
    return render_template('system_template/email_conf.html', form=form)


# 存储配置
@sys_bp.route('/save_conf', endpoint='save_conf', methods=['GET', 'POST'])
@login_required
def save_conf():
    save_obj = TL_Save_Model.query.first()
    if request.method == 'POST':
        return edit_data(TL_Save_Form, TL_Save_Model, db, save_obj.id)
    form = TL_Save_Form(data=dict(save_obj))
    return render_template('system_template/save_conf.html', form=form)
